import axios from 'axios'
import qs from 'qs'
import {
  apiBasePath
} from '@/api/config'
import {
  UserStore
} from '@/store/user'

axios.defaults.timeout = 3 * 1000
axios.defaults.baseURL = apiBasePath



axios.interceptors.response.use(
  response => {
    const data = response.data
    const code = data.code
    if (code === 403) {
      window.location.href = '/#/login'
    }
    return response
  },
  error => {
    console.error(error)
    return Promise.reject({
      code: 500,
      message: '服务器出错'
    })
  }
)

axios.interceptors.request.use(
  config => {
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('_site_token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)



function get(url, params) {
  return new Promise((resolve) => {
    axios
      .get(url, {
        params: params,
        paramsSerializer: params => {
          return qs.stringify(params, {
            indices: false,
            arrayFormat: 'repeat'
          })
        },
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      })
      .then(res => {
        if (res) {
          const data = res.data
          resolve({
            code: data.code,
            data: data.data || '',
            err: data.code === 200 ? void 0 : data.message
          })
        }
      })
      .catch(e => {
        console.error(e)
        resolve({
          code: 500,
          data: '',
          err: e.message
        })
      })
  })
}

function post(url, data) {
  return new Promise((resolve) => {
    axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      }).then(res => {
        const data = res.data
        resolve({
          code: data.code,
          data: data.data || '',
          message: data.message || '',
          err: data.code === 200 ? void 0 : data.message
        })
      })
      .catch(e => {
        console.log(e);
        resolve({
          code: 500,
          data: '',
          err: e.message
        })
      })
  })
}

function download(url, params = {}, callback) {
  axios({
    url: url,
    method: 'get',
    params: params,
    onDownloadProgress(progress) {
      if (callback) {
        let percent = Math.round((progress.loaded / progress.total) * 100)
        callback(percent)
      }
    },
    timeout: 0,
    responseType: 'blob'
  }).then(res => {
    if (res) {
      let blob = new Blob([res.data])
      let href = window.URL.createObjectURL(blob)
      let cd = res.headers['content-disposition']
      let re = new RegExp('filename=(.*)')
      let result = re.exec(cd)
      let filename = result[1]
      let de = document.createElement('a')
      de.href = href
      de.download = filename
      de.style.display = 'none'
      document.body.appendChild(de)
      de.click()
      document.body.removeChild(de)
      window.URL.revokeObjectURL(href)
    }
  })
}

export default {
  get,
  post,
  download
}
